package com.king.utils;

import com.baidu.aip.ocr.AipOcr;
import com.king.config.GlobalConst;
import org.json.JSONObject;

import java.util.HashMap;

public class BaiduAip {

    //设置APPID/AK/SK
    private static final String APP_ID = GlobalConst.getConfig("BAIDU_APP_ID");
    private static final String API_KEY = GlobalConst.getConfig("BAIDU_API_KEY");
    private static final String SECRET_KEY = GlobalConst.getConfig("BAIDU_SECRET_KEY");

    private static AipOcr client;
    private static AipOcr getClient(){
        // 初始化一个AipOcr
        if(client == null){
            client = new AipOcr(APP_ID, API_KEY, SECRET_KEY);
        }

        return client;
    }

    /**
     * 新建一个AipOcr,初始化完成后建议单例使用,避免重复获取access_token
     * @param imagePath
     */
    public static String getStrByLocalImage(String imagePath) {
        AipOcr client = getClient();

        // 可选：设置网络连接参数
        client.setConnectionTimeoutInMillis(2000);
        client.setSocketTimeoutInMillis(60000);

        // 可选：设置代理服务器地址, http和socket二选一，或者均不设置
        //client.setHttpProxy("proxy_host", proxy_port);  // 设置http代理
        //client.setSocketProxy("proxy_host", proxy_port);  // 设置socket代理

        // 可选：设置log4j日志输出格式，若不设置，则使用默认配置
        // 也可以直接通过jvm启动参数设置此环境变量
        //System.setProperty("aip.log4j.conf", "path/to/your/log4j.properties");

        // 调用接口
        JSONObject res = client.basicGeneral(imagePath, new HashMap<>());
        return res.toString(2);
    }

    public static String getStrByImageByte(byte[] file) {
        AipOcr client = getClient();

        // 传入可选参数调用接口
        HashMap<String, String> options = new HashMap<String, String>();
        options.put("language_type", "CHN_ENG");
        options.put("detect_direction", "true");
        options.put("detect_language", "true");
        options.put("probability", "true");

        // 参数为本地图片路径
        //String image = "test.jpg";
        //JSONObject res = client.basicGeneral(image, options);
        //System.out.println(res.toString(2));

        // 参数为本地图片二进制数组
        JSONObject res = client.basicGeneral(file, options);
        return res.toString(2);


        // 通用文字识别, 图片参数为远程url图片
        //JSONObject res = client.basicGeneralUrl(url, options);
        //System.out.println(res.toString(2));
    }

    public static String getStrByImageUrl(String imageUrl){
        AipOcr client = getClient();

        // 传入可选参数调用接口
        HashMap<String, String> options = new HashMap<>();
        options.put("language_type", "CHN_ENG");
        options.put("detect_direction", "true");
        options.put("detect_language", "true");
        options.put("probability", "true");

        JSONObject res = client.basicGeneralUrl(imageUrl, options);
        return res.toString(2);
    }
}
